/*
 * @Date: 2022-03-22 10:02:11
 * @LastEditTime: 2022-03-25 10:59:35
 */
// pages/techingPositions/index/index.js
import { store } from '../../../store/store';
import util from "../../../utils/util.js"
import {
  createStoreBindings,
  storeBindingsBehavior,
} from 'mobx-miniprogram-bindings';
const computedBehavior = require('miniprogram-computed').behavior;
const citySelector = requirePlugin('citySelector');
const key = 'DL6BZ-5X5CO-2VZWJ-SY6UO-UERNS-BIBLP'; // 使用在腾讯位置服务申请的key
const referer = '招教岗位通'; // 调用插件的app的名称
var QQMapWX = require('../../../utils/qqmap/qqmap-wx-jssdk.min');
var qqmapsdk;
var app = getApp()

Page({
  behaviors: [storeBindingsBehavior, computedBehavior],
  /**
   * 页面的初始数据
   */
  data: {
    isLogin: false,
    isShowAddBox: true,
    isShowAddPopUP: false,
    isAuthLocation: false,
    isSelectedCity: false,
    swiperIndex: 0,
    swiperData: [
      {
        id: 1,
        url: 'https://636c-cloud1-8ggeumhe5b48fafe-1307972625.tcb.qcloud.la/cloudbase-cms/upload/2022-04-07/99ra5t0u8lyy319vpa87dird8unes2o1_.jpg',
      },
      {
        id: 2,
        title:"ddd0",
        url: 'https://636c-cloud1-8ggeumhe5b48fafe-1307972625.tcb.qcloud.la/cloudbase-cms/upload/2022-04-07/99ra5t0u8lyy319vpa87dird8unes2o1_.jpg',
      },
      {
        id: 3,
        url: 'https://ws.dly.huikaoedu.com/upload/20220309/bf1422f9b33df44712d1d0ee9c2871ed.jpg',
      },
      {
        id: 4,
        url: 'https://ws.dly.huikaoedu.com/upload/20220309/b1a6a8385f0569815c27a3064616df8f.gif',
      },
      {
        id: 5,
        url: 'https://ws.dly.huikaoedu.com/upload/20220309/735661e5181e483d00e1722b9ef8120d.jpg',
      },
    ],
    iconData: [
      {
        id: 1,
        src: '/assets/techingPositions/icons_job_recruitment.png',
        text: '岗位招聘',
        tips: '岗位筛选说明',
        page:'/pages/techingPositions/jobRecruit/jobRecruit'
      },
      {
        id: 2,
        src: '/assets/techingPositions/icons_recruitment_announcement.png',
        text: '招考公告',
        tips: '招考公告说明',
        page:'/pages/recruitDynamics/new/more-news/more-news?type=0'
      },
      {
        id: 3,
        src: '/assets/techingPositions/icons_exam_preparation.png',
        text: '教招备考',
        tips: '掌上教师招考',
        page:'exam'
      },
      {
        id: 4,
        src: '/assets/techingPositions/icons_surrounding_malls.png',
        text: '周边商城',
        tips: '创世微信商城',
      },
    ],
    postData: [],
  },
  format:function(release_time) {
    const time_a = util.formatTime(new Date(release_time)) //此时得到形如2021-11-23
    // console.log(time_a)
    const year = time_a.substr(0, 4)
    let month = time_a.substr(5, 2)
    let day = time_a.substr(8, 2)
    //去掉前导0
    if (month[0] == '0') {
      month = month.substring(1)
    }
    if (day[0] == '0') {
      day = day.substring(1)
    }
    const time_b = year + '-' + month + "-" + day  //此时得到形如2021-11-23
    // console.log(time_b)
    return time_b;
  },
  getMenuButtonRect() {
    const { top, right, bottom, width, height } =
      wx.getMenuButtonBoundingClientRect();
    this.setData({
      capsuleTop: top,
      capsuleRight: right,
      capsuleBottom: bottom,
      capsuleWidth: width,
      capsuleHeight: height,
      paddingRight: 375 - right,
    });
  },
  getSetting() {
    let { isAuthLocation } = this.data;
    wx.getSetting({
      success: (res) => {
        const locationAuth = res.authSetting['scope.userLocation'];
        isAuthLocation =
          typeof locationAuth != 'undefined' && !locationAuth ? false : true;
        this.setData({ isAuthLocation });
      },
      fail: (err) => {
        console.log(err);
      },
      complete: () => {
        this.classifyLocationAuth(isAuthLocation);
      },
    });
  },
  classifyLocationAuth(isAuthLocation) {
    const { isGotCurrLocation, isSelectedCity } = this.data;
    if (isAuthLocation) {
      this.reset();
      if (isSelectedCity) {
        // 从更换定位城市页面返回
        this.handleSetCity();
      } else if (!isGotCurrLocation) {
        // 第一次进入首页
        this.getLocation();
      } else {
        // 已获取用户定位
        // this.getList()
        console.log('classifyLocationAuth：getList');
      }
    } else {
      wx.showModal({
        title: '提示',
        content: '您拒绝了定位权限，将无法使用工作推荐功能',
        success: (toastRes) => {
          const { confirm, cancel } = toastRes;
          if (confirm) {
            wx.openSetting();
            setTimeout(() => {
              store.SET_ISGOTCURRLOCATION(true);
            }, 2000);
          }
          if (cancel) {
            wx.showToast({ title: '您拒绝了定位权限', icon: 'none' });
            // this.getSettingTimeout = setTimeout(() => {
            //   this.getSetting();
            // }, 3000);
          }
        },
      });
    }
  },
  reset() {
    wx.pageScrollTo({ scrollTop: 0, duration: 300 });
  },
  getLocation() {
    wx.getLocation({
      type: 'wgs84',
      isHighAccuracy: true,
      // highAccuracyExpireTime: 2500,
      success: (getLocationRes) => {
        const { latitude, longitude } = getLocationRes;
        // 经纬度-->地级市
        qqmapsdk.reverseGeocoder({
          location: { latitude, longitude },
          success: (reverseRes) => {
            const { adcode, province, city } = reverseRes.result.ad_info;
            let current = {province, city, latitude, longitude, adcode };
            console.log(current);
            this.setData({ current });
            app.globalData.currentPos = current
            store.SET_ISGOTCURRLOCATION(true);
            // this.getList();
            console.log('getLocation：getList');
            app.initCloudFunction().then(cloud=>{
              cloud.callFunction({
                name: 'get_new_lunbo',
                }).then(res => {
                let ans = res.result.data;
                let s = []
                for (let i = 0; i < ans.length; i++) {
                  ans[i].id = i
                    s.push(ans[i]);
                }
                console.log("lunbo:--------", s)
                this.setData({
                  swiperData: s
                })
            })
              cloud.callFunction({
                name:'getPost',
                data:{
                  Action:'getThreePosts',
                  province:this.data.current.province,
                  city:this.data.current.city
                },
                success:res =>{
                 /*res.result.data.forEach(item=>{
                    item.endTime = item.endTime.replace('年','-')
                    item.endTime = item.endTime.replace('月','-')
                    item.startTime = item.startTime.replace('年','-')
                    item.startTime = item.startTime.replace('月','-')
                    item.status++
                  })*/
                  for(let i = 0;i< res.result.data.length ; i++){
                    res.result.data[i].registration_begin = this.format(res.result.data[i].registration_begin)
                    res.result.data[i].registration_end = this.format(res.result.data[i].registration_end)
                  }
                  this.setData({
                    postData:res.result.data
                  })
                }
              })
            })
          },
        });
      },
      fail: (err) => {
        const { num } = this.data;
        this.setData({ num: num + 1 });
        if (num == 5) {
          this.handleChangeLocation();
          this.setData({ num: 1 });
        } else {
          this.getSetting();
        }
      },
    });
  },
  handleShow(e) {
    let { type } = e.currentTarget.dataset;
    switch (Number(type)) {
      case 0:
        this.setData({ isShowAddBox: false });
        break;
      case 1:
      case 2:
        this.setData({ isShowAddPopUP: !this.data.isShowAddPopUP });
        break;
    }
  },
  handleChangeLocation() {
    const hotCitys = ''; // 用户自定义的的热门城市
    wx.navigateTo({
      url: `plugin://citySelector/index?key=${key}&referer=${referer}&hotCitys=${hotCitys}`,
    });
    this.setData({ isSelectedCity: true });
  },
  handleSetCity() {
    // 选择城市后返回城市信息对象，若未选择返回null
    const { id, fullname, location } = citySelector.getCity() || {};
    console.log(citySelector.getCity());
    if (id) {
      console.log(id);
      const current = {
        adcode: id,
        city: fullname,
        latitude: location.latitude,
        longitude: location.longitude,
      };
      this.setData({ current });
    }
    // this.getList()
    console.log('handleSetCity：getList');
  },
  go2Follow() {
    const url =
      'https://mp.weixin.qq.com/s?__biz=MzkyMjMyNTU2Ng==&mid=2247483655&idx=1&sn=17ab734957915585dfef69d818f36583';
    const str = encodeURIComponent(JSON.stringify(url));
    wx.$go2('/pages/webview/webview?src=' + str, false);
    store.SET_ISGO2FOLLOW(true);
  },
  go2login() {
    wx.$go2('/pages/personalCenter/login/login', false);
  },
  go2Page:function(e){
    let page = e.currentTarget.dataset.page
    if(page==='exam'){
      console.log('打开小程序')
      wx.navigateToMiniProgram({
        appId:'wxf5e4826a10e37e11',
        envVersion: 'release',// 打开正式版
        success(res) {
        // 打开成功
        },
        fail: function (err) {
          console.log(err);
        }
      })
    }else{
      console.log('跳转'+page)
      wx.$go2(page,false);
    }
    
  },
  go2Detail(e){
    let id = e.currentTarget.dataset.id
    wx.$go2("/pages/techingPositions/jobDetails/jobDetails?ID="+id,false);
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    qqmapsdk = new QQMapWX({
      key,
    });
    this.storeBindings = createStoreBindings(this, {
      store,
      fields: ['token', 'isGo2Follow', 'isGotCurrLocation'],
      actions: ['SET_ISGO2FOLLOW', 'SET_ISGOTCURRLOCATION'],
    });
    this.getMenuButtonRect();
  },
  onShow: function () {
    var isLogin = wx.getStorageSync('isLogin')
    if(isLogin == undefined){
      isLogin = false
    }
    console.log("isLogin:",isLogin)
    console.log("true_islogin:",this.data.isLogin)
    setTimeout(() => {
      // this.setData({ isLogin: this.data.token ? true : false });
      this.setData({isLogin: isLogin})
    }, 100);
    this.getSetting();
  },
  onUnload: function () {
    // 页面卸载时清空插件数据，防止再次进入页面，getCity返回的是上次的结果
    citySelector.clearCity();
  },
  goDetail(e) {
    console.log("eeee:",e)
    // var link = e.currentTarget.dataset.link;
    // var type = e.currentTarget.dataset.type;
    // console.log("link:-------", link)
    // console.log("type:------", type)
    // wx.setStorageSync('link', link)
    // //如果是功能页面
    // if (type == "function") {
    //     wx.navigateTo({
    //         url: '../../pages/function-introduction/function-introduction',
    //     })
    // } else if (type == "gzh") {
    //     console.log("gzh----------------------------------")
    //     console.log("link", link)
    //     e.currentTarget.dataset.link = link
    //     this.toGzhPost(e)
    // } else {
    //     //查找对应的_id
    //     wx.cloud.callFunction({
    //         name: "getIndexInfo",
    //         data: {
    //             sign: 27,
    //             type: type,
    //             link: link
    //         }
    //     }, ).then(res => {
    //         console.log("res:", res.result.data)
    //         let temp = res.result.data[0]
    //         if (!temp) {
    //             wx.showToast({
    //                 title: '该公告未录入,敬请期待',
    //                 icon: 'none',
    //                 duration: 2000,
    //             })
    //         } else {
    //             var id = temp._id
    //             console.log("id------------:", id)
    //             //找到对应类型公告
    //             if (type == "notice") {
    //                 wx.navigateTo({
    //                     url: '../../pages/Notice_detail/Notice_detail?_id=' + id,
    //                 })
    //             } else if (type == "news") {
    //                 wx.navigateTo({
    //                     url: '../../pages/news_detail/news_detail?_id=' + id,
    //                 })
    //             } else if (type == "policy") {
    //                 wx.navigateTo({
    //                     url: '../../pages/policy_detail/policy_detail?_id=' + id,
    //                 })
    //             } else if (type == "employ_notice") {
    //                 wx.navigateTo({
    //                     url: '../../pages/publishList_detail/1?_id=' + id,
    //                 })
    //             }
    //         }
    //     })
    // }
},
 //轮播图的切换事件  
 swiperChange: function (e) { 
   console.log("轮播图切换了：",e)
  this.setData({
    swiperIndex: e.detail.swiperCurrent   //获取当前轮播图片的下标
  })
},
//点击指示点切换  
chuangEvent: function (e) {
  console.log("tap :",e)
  this.setData({
    swiperCurrent: e.currentTarget.id
  })
},
});
